<script setup>
	import {
		onLaunch,
		onShow,
		onError
	} from '@dcloudio/uni-app';
	import {
		ShoproInit
	} from './sheep';
	import {
		reactive
	} from 'vue';
	import DeliveryApi from '@/sheep/api/trade/delivery';
	import sheep from '@/sheep';

	const LONGITUDE = 'user_longitude';
	const LATITUDE = 'user_latitude';
	const state = reactive({
		loaded: false,
		loading: false,
		storeList: [],
		system_store: {},
		locationShow: false,
		user_latitude: 0,
		user_longitude: 0,
	});

	onLaunch(async (options) => {
		// 检查是否有扫描的链接参数
		const hasScanUrl = options.query?.q || options.query?.tenantId || options.query?.storeId;

		// 如果有扫描的链接参数，处理扫描逻辑
		if (hasScanUrl) {
			// 处理扫描链接的参数
			if (options.query?.tenantId) {
				sheep.$store('user').handleSetTenantId(options.query.tenantId);
			} else {
				sheep.$store('user').handleSetTenantId();
			}

			if (options.query?.storeId) {
				const {
					data
				} = await DeliveryApi.getDeliveryPickUpStoreList();
				if (data.length) {
					sheep.$store('selectStore').setSelect(data.find(item => item.id == options.query.storeId));
				}
			}

			if (options.query?.q) {
				const q = decodeURIComponent(options.query.q);
				// 提取查询字符串部分
				const queryString = q.split('?')[1];

				// 将查询字符串分割成键值对
				const params = {};
				queryString.split('&').forEach(pair => {
					const [key, value] = pair.split('=');
					params[decodeURIComponent(key)] = decodeURIComponent(value);
				});

				// 获取 tenantId 和 storeId
				const tenantId = params.tenantId;
				const storeId = params.storeId;

				sheep.$store('user').handleSetTenantId(params.tenantId);

				const {
					data
				} = await DeliveryApi.getDeliveryPickUpStoreList();
				sheep.$store('selectStore').setSelect(data.find(item => item.id == params.storeId));
			}

			ShoproInit();
			return; // 直接返回，不执行后续逻辑
		}

		// 如果没有扫描的链接参数，检查是否有经纬度
		state.user_latitude = uni.getStorageSync(LATITUDE);
		state.user_longitude = uni.getStorageSync(LONGITUDE);

		if (state.user_latitude && state.user_longitude) {
			// 如果有经纬度，执行 getList
			getList();
		} else {
			// 如果没有经纬度，执行 initSheep 和 selfLocation
			try {
				await initSheep();
				selfLocation();
			} catch (error) {
				console.error('初始化失败', error);
			}
		}
	});

	onShow(async (options) => {
		// // #ifdef H5
		// if (options.query?.tenantId) {
		// 	sheep.$store('user').handleSetTenantId(options.query?.tenantId);
		// } else {
		// 	sheep.$store('user').handleSetTenantId();
		// }
		// if (options.query?.storeId) {
		// 	const {
		// 		data
		// 	} = await DeliveryApi.getDeliveryPickUpStoreList();
		// 	if (data.length) {
		// 		sheep.$store('selectStore').setSelect(data.find(item => item.id == options.query?.storeId))
		// 	}
		// }
		// // #endif
		// // #ifdef MP-WEIXIN
		// if (options.query?.q) {
		// 	const q = decodeURIComponent(options.query.q);
		// 	// 提取查询字符串部分
		// 	const queryString = q.split('?')[1];

		// 	// 将查询字符串分割成键值对
		// 	const params = {};
		// 	queryString.split('&').forEach(pair => {
		// 		const [key, value] = pair.split('=');
		// 		params[decodeURIComponent(key)] = decodeURIComponent(value);
		// 	});
		// 	// 获取 tenantId 和 storeId
		// 	const tenantId = params.tenantId;
		// 	const storeId = params.storeId;
		// 	sheep.$store('user').handleSetTenantId(params.tenantId);
		// 	const {
		// 		data
		// 	} = await DeliveryApi.getDeliveryPickUpStoreList();
		// 	sheep.$store('selectStore').setSelect(data.find(item => item.id == params.storeId))
		// }
		// // #endif
		// #ifdef APP-PLUS
		// 获取urlSchemes参数
		const args = plus.runtime.arguments;
		if (args) {}

		// 获取剪贴板
		uni.getClipboardData({
			success: (res) => {},
		});
		// #endif
	});

	const selfLocation = () => {
		// #ifdef H5
		const jsWxSdk = sheep.$platform.useProvider('wechat').jsWxSdk;
		if (jsWxSdk.isWechat()) {
			jsWxSdk.getLocation((res) => {
				state.user_latitude = res.latitude;
				state.user_longitude = res.longitude;
				uni.setStorageSync(LATITUDE, res.latitude);
				uni.setStorageSync(LONGITUDE, res.longitude);
				getList();
			});
		} else {
			// #endif
			uni.getLocation({
				type: 'gcj02',
				success: (res) => {
					try {
						state.user_latitude = res.latitude;
						state.user_longitude = res.longitude;
						uni.setStorageSync(LATITUDE, res.latitude);
						uni.setStorageSync(LONGITUDE, res.longitude);
					} catch (e) {
						console.error(e);
					}
					getList();
				},
				complete: () => {
					getList();
				},
				fail: (error) => {
					console.log(error);
				},
			});
			// #ifdef H5
		}
		// #endif
	};

	/**
	 * 获取门店列表数据
	 */
	async function getList() {
		if (state.loading || state.loaded) {
			return;
		}
		state.loading = true;
		const {
			data,
			code
		} = await DeliveryApi.getDeliveryPickUpStoreList({
			latitude: state.user_latitude,
			longitude: state.user_longitude,
		});
		if (code !== 0) {
			return;
		}
		state.loading = false;
		state.storeList = data;
		if (data.length) {
			sheep.$store('selectStore').setSelect(data[0]);
		}

		// 延时隐藏原生导航栏
		setTimeout(() => {
			uni.hideTabBar();
		}, 200);
		// 加载Shopro底层依赖
		ShoproInit();
	}

	async function initSheep() {
		const jsWxSdk = sheep.$platform.useProvider('wechat').jsWxSdk;
		if (!jsWxSdk) {
			console.error('jsWxSdk 未正确初始化');
			return;
		}
		return new Promise((resolve) => {
			jsWxSdk.init(() => {
				resolve();
			});
		});
	}
</script>

<style lang="scss">
	@import '@/sheep/scss/index.scss';
</style>